package com.wlyuan.open.domain.service.dingtong;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wlyuan.open.domain.PushBusinessType;
import com.wlyuan.open.domain.PushTask;
import com.wlyuan.open.domain.repository.PushTaskRepository;
import com.wlyuan.open.domain.service.PushStrategy;
import com.wlyuan.open.vo.push.order.OrderDetailVO;
import com.wlyuan.open.vo.push.track.TrackDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author 顶通推送
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DingTongPushStrategy implements PushStrategy {

    private final PushTaskRepository pushTaskRepository;


    @Override
    public void handle(PushTask pushTask) {
        sendDTPost(pushTask);
        pushTaskRepository.save(pushTask);
    }


    private DingTongRequest getRequestBody(PushTask pushTask) {
        DingTongRequest dingTongRequest = new DingTongRequest();
        if (pushTask.getBusinessType().equals(PushBusinessType.ORDER_SIGNED)) {
            var order = pushTask.getBusinessInfo().toJavaObject(OrderDetailVO.class);
            if (order != null && order.getSign() != null) {
                dingTongRequest.setPactCode(order.getContractNo());
                dingTongRequest.setSignTime(Date.from(order.getSignTime().atZone(ZoneId.systemDefault()).toInstant()));
                dingTongRequest.setFailDescription(order.getSign().getRemarks());
                dingTongRequest.setStatus("600");
                if (CollectionUtil.isNotEmpty(order.getSign().getAttachments())) {
                    for (int i = 0; i < order.getSign().getAttachments().size(); i++) {
                        var signUrl = order.getSign().getAttachments().get(i).getUrl();
                        if (i == 0) {
                            dingTongRequest.setPic1(signUrl);
                        } else if (i == 1) {
                            dingTongRequest.setPic2(signUrl);
                        } else if (i == 2) {
                            dingTongRequest.setPic3(signUrl);
                        } else if (i == 3) {
                            dingTongRequest.setPic4(signUrl);
                        } else if (i == 4) {
                            dingTongRequest.setPic5(signUrl);
                        } else if (i == 5) {
                            dingTongRequest.setPic6(signUrl);
                        }
                    }
                }
                if (StringUtils.isNotBlank(order.getSign().getLocation())) {
                    var locations = order.getSign().getLocation().split(",");
                    dingTongRequest.setLon(new BigDecimal(locations[0]));
                    dingTongRequest.setLat(new BigDecimal(locations[1]));
                }
            }
        } else {
            TrackDetailVO trackingVO = pushTask.getBusinessInfo().toJavaObject(TrackDetailVO.class);
            if (trackingVO != null) {
                dingTongRequest.setPactCode(trackingVO.getContractNo());
                if (pushTask.getBusinessType().equals(PushBusinessType.TRACK_SET_OUT)
                        || pushTask.getBusinessType().equals(PushBusinessType.TRACK_REAL_FROM)) {
                    dingTongRequest.setLeaveWarehouseTime(trackingVO.getTime());
                    dingTongRequest.setStatus("400");
                } else if (pushTask.getBusinessType().equals(PushBusinessType.TRACK_REACH)) {
                    dingTongRequest.setArriveShippointTime(trackingVO.getTime());
                    dingTongRequest.setStatus("500");
                }
                if (trackingVO.getLatitude() != null) {
                    dingTongRequest.setLat(new BigDecimal(trackingVO.getLatitude()));
                }
                if (trackingVO.getLongitude() != null) {
                    dingTongRequest.setLon(new BigDecimal(trackingVO.getLongitude()));
                }
            }
        }
        return dingTongRequest;
    }

    private void sendDTPost(PushTask pushTask) {
        Boolean isSuccess = false;
        HttpResponse response = null;
        String responseData = "";
        StringBuilder url = new StringBuilder("");
        DingTongRequest dingTongRequest = null;
        try {
            dingTongRequest = getRequestBody(pushTask);
            url.append(pushTask.getRequestUrl());
            url.append("pactCode=").append(dingTongRequest.getPactCode());
            url.append("&status=").append(dingTongRequest.getStatus());
            url.append("&lon=").append(dingTongRequest.getLon());
            url.append("&lat=").append(dingTongRequest.getLat());
            url.append("&leaveWarehouseTime=");
            if (dingTongRequest.getLeaveWarehouseTime() != null) {
                url.append(URLEncoder.encode(DateUtil.format(dingTongRequest.getLeaveWarehouseTime(), "yyyy-MM-dd HH:mm:ss"), "utf-8"));
            } else {
                url.append(dingTongRequest.getLeaveWarehouseTime());
            }
            url.append("&arriveShippointTime=");
            if (dingTongRequest.getArriveShippointTime() != null) {
                url.append(URLEncoder.encode(DateUtil.format(dingTongRequest.getArriveShippointTime(), "yyyy-MM-dd HH:mm:ss"), "utf-8"));
            } else {
                url.append(dingTongRequest.getArriveShippointTime());
            }
            url.append("&signTime=");
            if (dingTongRequest.getSignTime() != null) {
                url.append(URLEncoder.encode(DateUtil.format(dingTongRequest.getSignTime(), "yyyy-MM-dd HH:mm:ss"), "utf-8"));
            } else {
                url.append(dingTongRequest.getSignTime());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getMark())) {
                url.append("&mark=").append(dingTongRequest.getMark());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getFailDescription())) {
                url.append("&failDescription=").append(URLEncoder.encode(dingTongRequest.getFailDescription(), "UTF-8"));
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic1())) {
                url.append("&pic1=").append(dingTongRequest.getPic1());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic2())) {
                url.append("&pic2=").append(dingTongRequest.getPic2());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic3())) {
                url.append("&pic3=").append(dingTongRequest.getPic3());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic4())) {
                url.append("&pic4=").append(dingTongRequest.getPic4());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic5())) {
                url.append("&pic5=").append(dingTongRequest.getPic5());
            }
            if (StringUtils.isNotBlank(dingTongRequest.getPic6())) {
                url.append("&pic6=").append(dingTongRequest.getPic6());
            }
            HttpRequest request = HttpRequest.post(url.toString());
            request.header("Content-Type", "application/json");
            request.timeout(30000);
            response = request.execute();
            JSONObject data = JSONUtil.parseObj(response.body());
            if (response.isOk()) {
                if (data != null) {
                    isSuccess = (Boolean) data.get("success");
                }
            }
            if (isSuccess) {
                pushTask.success(pushTask.getRequestUrl(), url.toString(), data.toString());
            } else {
                responseData = data.toString();
                pushTask.fail(pushTask.getRequestUrl(), url.toString(), data.toString(), "失败");
            }
            logger.info("==========请求地址：{},======body:{}", url, response.body());
        } catch (Exception e) {
            logger.error("=====推送顶通出错,请求地址：" + url, e);
            pushTask.fail(pushTask.getRequestUrl(), url.toString(), responseData, "失败:" + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


}
